import React,{useState,useEffect,useCallback} from 'react';
import Cookie from 'react-cookies';
import request from "../../../../assets/js/pc/utils/request";
import {message,Form} from 'antd';
import actions from "../../../../store/actions";
function hoc(WithComponent){
    return function useHocComponent(props){
        const {dispatch,state,history} =props;
        const {redLogin} = state;
        const [imageUrl, setImageUrl] = useState();
        const [useId, setUseId] = useState();
        const [useName, setUseName] = useState();
        const [useEmail, setUseEmail] = useState();
        const [useRole, setUseRole] = useState();
        const [loading, setLoading] = useState(false);
        const [isInputEdit, setIsInputEdit] = useState(true);
        const [isPassWordEdit, setIsPassWordEdit] = useState(false);
        const [formInput] = Form.useForm();
        const [formPassWord] = Form.useForm();
        //检测上传文件类型
        const beforeUpload = (file) => {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                message.error('You can only upload JPG/PNG file!');
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('Image must smaller than 2MB!');
            }
            return isJpgOrPng && isLt2M;
        };
        //图片转换Base64
        const getBase64 = (img, callback) => {
            const reader = new FileReader();
            reader.addEventListener('load', () => callback(reader.result));
            reader.readAsDataURL(img);
        };
        const handleChange = (info) => {
            if (info.file.status === 'uploading') {
                setLoading(true);
                return;
            }
            if (info.file.status === 'done') {
                setLoading(false);

                let ursl = `${window.base.config.baseUrlShop}user/myinfo/formdatahead?token=${window.base.config.token}`;
                let data = {
                    headfile:info.file.originFileObj
                }
                request(ursl,'file',data).then((res)=>{ //图片上传
                    let rUrl = `${window.base.config.baseUrlShop}user/myinfo/updateuser?token=${window.base.config.token}`;
                    let rData = {
                        uid:props.state.redLogin.uId,
                        head:res.data.msbox,
                        nickname:useName,
                        gender:2,
                    }
                    request(rUrl,'post',rData).then((res)=>{ //提交保存图片
                        if (res.code === 200){
                            getBase64(info.file.originFileObj, (url) => {
                                setImageUrl(url)
                            });

                        }
                    })
                })



            }
        };
        //开启编辑用户名
        const isInputEditBtn = ()=>{
            setIsInputEdit(false)
        }
        //取消编辑用户名
        const inputCancel = ()=>{
            setIsInputEdit(true)
        }
        //提交用户名
        const formInputOnFinish = (value)=>{
            let loginType =Cookie.load('loginType')
            if (loginType === 'login'){
                let url =  window.base.config.baseUrlShop + 'user/myinfo/updateuser?token=' + window.base.config.token,
                    data = {
                        uid:props.state.redLogin.uId,
                        nickname:value.username,
                        gender:2,
                    };
                request(url,'post',data).then((res)=>{
                    if (res.code === 200){
                        // getUserInfo()
                        setUseName(value.username);
                    }
                })
            }else if (loginType === 'gite'){
                setUseName(1111)
            }

            setIsInputEdit(true)
        }
        //开启编辑修改密码
        const personalPassWordBtn = ()=>{
            setIsPassWordEdit(true)
        }
        //取消编辑修改密码
        const passWordCancleBtn = ()=>{
            formPassWord.resetFields()//清空表格
            setIsPassWordEdit(false)
        }
        //修改密码提交按钮
        const passwordChenge = (value )=>{
            let url = `${window.base.config.baseUrlShop}user/myinfo/modpwd?token=${window.base.config.token}`,
                data={
                    uid:state.redGetUseInfo.uid,
                    password:value.password
                };
            request(url,'post', data).then((res)=>{
                console.log(res)
                if (res.code === 200){
                    setIsPassWordEdit(false)
                }
            })
        }
        //获取第三方登录信息
        const getThirdUserInfo = useCallback(() => {
            let data = {
                access_token:Cookie.load('access_token')
            };
            if (data.access_token !== undefined){
               dispatch(actions.actGetUseInfo.actGetThirdUseInfo({
                    data,
                    success:(res)=>{
                        setUseName(res.useName)
                        setImageUrl(res.useHeadImg)
                        setUseId(res.useId)
                        setUseEmail('asd')
                        setUseRole(res.useRole)
                    }
                }))
            }
        },[dispatch]);
        //获取登录信息
        const getUserInfo = useCallback(()=>{
            let token =Cookie.load('access_token');
            if (token !== undefined){
                let data={
                    uId:redLogin.uId
                };
                dispatch(actions.actGetUseInfo.actGetUserInfo({
                    data,
                    success:(res)=>{
                        setUseName(res.data.nickname)
                        setImageUrl(res.data.head)
                        setUseId(res.data.uid)
                        setUseEmail('asd')
                        setUseRole(res.data.utype)
                    }
                }))
            }
        },[redLogin.uId,dispatch])
        //判断没有登录跳转登录页面
        const isLoginGoPage = useCallback(()=>{
            let token =Cookie.load('access_token');
            if (token === undefined){
                dispatch(actions.actLogin.actOutLogin( {
                    success:()=>{
                        history.replace(window.base.config.path+'login')
                    }
                }))
            }
        },[dispatch,history])
        useEffect(()=>{
            isLoginGoPage()
            let loginType =Cookie.load('loginType')
            if (loginType === 'gite'){
                //加载第三方用户信息
                getThirdUserInfo()
            }else if (loginType === 'login'){
                getUserInfo()
            }
        },[getThirdUserInfo,getUserInfo,isLoginGoPage,useName,imageUrl,state.redGetUseInfo.useHeadImg])

        let newProps={
            imageUrl:imageUrl,
            useName:useName,
            useEmail:useEmail,
            useRole:useRole,
            useId:useId,
            loading:loading,
            isInputEdit:isInputEdit,
            fromInput:formInput,
            formPassWord:formPassWord,
            isPassWordEdit:isPassWordEdit,
            handleChange:handleChange.bind(this),
            beforeUpload:beforeUpload.bind(this),
            isInputEditBtn:isInputEditBtn.bind(this),
            formInputOnFinish:formInputOnFinish.bind(this),
            inputCancel:inputCancel.bind(this),
            personalPassWordBtn:personalPassWordBtn.bind(this),
            passWordCancleBtn:passWordCancleBtn.bind(this),
            passwordChenge:passwordChenge.bind(this)
        }
        return (
            <WithComponent {...props} {...newProps}  />
        )
    }
}
export default hoc